package com.example.shardingjdbc.sharding.algorithm;

import com.example.shardingjdbc.utils.DateUtils;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Collection;
import java.util.Date;

import static com.example.shardingjdbc.model.constants.OperLogConstant.QUARTER_SHARDING_PATTERN;

/**
 * @Description: 操作日志精准分片算法
 * @Author: Jerry
 * @Date: 2021-08-02 23:13
 */
public class OperLogPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Date> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Date> shardingValue) {
        String logicTableName = shardingValue.getLogicTableName();

        Date value = shardingValue.getValue();
        LocalDate localDate = value.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        int year = localDate.getYear();
        int month = localDate.getMonthValue();
        int quarter = DateUtils.getQuarterFromMonth(month);

        String actualTableName = String.format(QUARTER_SHARDING_PATTERN.getVal(), logicTableName, year, quarter);
        if (availableTargetNames.contains(actualTableName)) {
            return actualTableName;
        }
        throw new IllegalArgumentException("分片异常！shardingValue=" + shardingValue + "; actualTableName=" + actualTableName);
    }
}
